# -*- coding: utf-8 -*-

"""
情感计算引擎
"""

import cv2
import numpy as np
import time
import threading
from PyQt5.QtCore import QObject, pyqtSignal


class EmotionEngine(QObject):
    # 定义信号，用于在检测到高焦虑值时通知场景切换
    anxiety_detected = pyqtSignal()
    
    def __init__(self):
        """初始化情感引擎"""
        super().__init__()
        self.emotion_model = None
        self.cap = None
        self.is_running = False
        self.current_emotions = {}
        self.anxiety_threshold = 0.7
        self.frame_rate = 5  # 控制帧率以优化性能
        self.load_model()
        
    def load_model(self):
        """加载情感模型"""
        try:
            # 尝试导入Affectiva SDK
            # 注意：实际使用时需要根据Affectiva SDK的Linux版本调整导入方式
            # 这里是一个示例接口
            print("加载Affectiva情感分析模型...")
            # self.emotion_model = AffectivaAPI()  # 实际的Affectiva SDK初始化
            self.emotion_model = "emotion_model_placeholder"
        except ImportError:
            print("警告: 未找到Affectiva SDK，使用模拟情感数据")
            self.emotion_model = None
            
    def start_camera_capture(self):
        """启动摄像头捕获"""
        if self.is_running:
            return
            
        self.cap = cv2.VideoCapture(0)
        if not self.cap.isOpened():
            print("错误: 无法打开摄像头")
            return
            
        self.is_running = True
        # 在单独线程中运行视频捕获循环
        self.capture_thread = threading.Thread(target=self._capture_loop)
        self.capture_thread.daemon = True
        self.capture_thread.start()
        
    def stop_camera_capture(self):
        """停止摄像头捕获"""
        self.is_running = False
        if self.cap:
            self.cap.release()
            
    def _capture_loop(self):
        """视频捕获循环"""
        last_process_time = 0
        frame_count = 0
        
        while self.is_running:
            ret, frame = self.cap.read()
            if not ret:
                continue
                
            current_time = time.time()
            
            # 控制帧率以优化性能
            if current_time - last_process_time >= 1.0 / self.frame_rate:
                # 处理帧并检测情绪
                emotions = self.analyze_frame_emotion(frame)
                self.current_emotions = emotions
                
                # 检查焦虑值是否超过阈值
                if emotions.get("anxiety", 0) > self.anxiety_threshold:
                    # 发出信号通知切换到治愈场景
                    self.anxiety_detected.emit()
                    
                last_process_time = current_time
                
            frame_count += 1
            # 短暂休眠以减少CPU使用率
            time.sleep(0.01)
            
    def analyze_frame_emotion(self, frame):
        """
        分析视频帧中的人脸情绪
        
        Args:
            frame (numpy.ndarray): 视频帧数据
            
        Returns:
            dict: 情感分析结果
        """
        # 如果有Affectiva SDK，使用实际模型分析
        if self.emotion_model and self.emotion_model != "emotion_model_placeholder":
            # 这里应该是实际调用Affectiva SDK的代码
            # emotions = self.emotion_model.detect_emotions(frame)
            # return emotions
            pass
            
        # 模拟情感数据（用于演示和测试）
        import random
        emotions = {
            "joy": random.uniform(0, 1),
            "sadness": random.uniform(0, 1),
            "anger": random.uniform(0, 1),
            "surprise": random.uniform(0, 1),
            "fear": random.uniform(0, 1),
            "disgust": random.uniform(0, 1),
            "anxiety": random.uniform(0, 1),  # 焦虑值
            "calm": random.uniform(0, 1)
        }
        
        # 确保焦虑值有时会超过阈值，用于测试
        if random.random() < 0.1:  # 10%概率
            emotions["anxiety"] = random.uniform(0.7, 1.0)
            
        return emotions
        
    def analyze_image_emotion(self, image_path):
        """
        分析图片情感
        
        Args:
            image_path (str): 图片路径
            
        Returns:
            dict: 情感分析结果
        """
        # 简化实现，实际应使用AI模型分析图片
        import random
        emotions = ["快乐", "悲伤", "平静", "兴奋", "忧郁"]
        emotion = random.choice(emotions)
        
        return {
            "dominant_emotion": emotion,
            "confidence": random.uniform(0.7, 0.95),
            "emotions": {e: random.uniform(0.1, 0.9) for e in emotions}
        }
        
    def suggest_puzzle_theme(self, emotion_data):
        """
        根据情感数据建议拼图主题
        
        Args:
            emotion_data (dict): 情感分析数据
            
        Returns:
            str: 推荐的拼图主题
        """
        emotion = emotion_data["dominant_emotion"]
        theme_map = {
            "快乐": "阳光明媚的风景",
            "悲伤": "宁静的雨景",
            "平静": "山水画",
            "兴奋": "城市夜景",
            "忧郁": "抽象艺术"
        }
        
        return theme_map.get(emotion, "自然风景")
        
    def get_current_emotions(self):
        """获取当前检测到的情绪"""
        return self.current_emotions